package com.bst.bsj.bops.web.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bst.bsj.base.controller.WebBaseController;
import com.bst.bsj.bops.web.biz.MemberService;
import com.bst.bsj.bops.web.biz.MessageService;
import com.bst.bsj.bops.web.biz.UserMessageService;
import com.bst.bsj.common.dal.dataobject.Message;
import com.bst.bsj.common.dal.dataobject.UserMessage;
import com.bst.bsj.common.maopu.enums.HasReadEnum;
import com.bst.bsj.common.maopu.enums.MemberStatus;
import com.bst.bsj.common.maopu.enums.MsgTypeEnum;
import com.bst.bsj.portal.util.StringUtil;
import com.homewaimai.common.lang.Paginator;
import com.homewaimai.common.lang.Result;

/**
* @Title: MessageController.java
* @Package com.bst.bsj.bops.web.controller
* @Description: 系统消息管理
* @author yj
* @date 2016年5月17日 上午10:42:14
* @version V1.0
* Copyright (c) 2015, 博思堂博视界.
 */
@Scope("prototype")
@Controller
@RequestMapping(value = "/bops/sys/message")
public class MessageController extends WebBaseController {

  @Autowired
  private MessageService messageService;
  @Autowired
  private UserMessageService userMessageService;
  @Autowired
  private MemberService memberService;

  /**
  * @Title: messageList
  * @Description: 消息跳转
  * @param req
  * @param resp
  * @return
  * @throws Exception
  * ModelAndView
  * @throws 
  * @creator     :yj
  * @create date :2016年5月17日 下午4:57:56
  * @modificator :yj
  * @modify date :2016年5月17日 下午4:57:56
   */
  @RequestMapping(value = "/message")
  public ModelAndView messageList(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    Map<String, Object> params = getBopsParams(req);
    ModelAndView modelAndView = getBopsModelAndView("management/message");
    
    String pageNums = (String) params.get("pageNum");
    Integer pageNum = 0;

    if (StringUtil.isNumeric(pageNums)) {
      pageNum = Integer.valueOf(pageNums);
    }
    if (pageNum == null || pageNum == 0) {
      pageNum = 1;
    }
    params.put("msgType", MsgTypeEnum.SYS.getCode());
    params.put("page", pageNum);
    params.put("length", 10);
    params.put("offset", new Long((pageNum - 1) * 10));

    Result result=messageService.query(params);
    // 如果请求成功
    if (result.isSuccess()) {
      // 得到分页器
      Paginator paginator = (Paginator) result.getModels().get("paginator");
      // 得到数据
      List<Message> messageList = (List<Message>) result.getModels().get("messageList");
      modelAndView.addObject("messageList", messageList);
      modelAndView.addObject("paginator", paginator);
    }
    modelAndView.addObject("params", params);
    return modelAndView;
  }
  
  /**
  * @Title: save
  * @Description: 保存系统消息
  * @param req
  * @param resp
  * @return
  * @throws Exception
  * ModelAndView
  * @throws 
  * @creator     :yj
  * @create date :2016年5月17日 下午4:58:15
  * @modificator :yj
  * @modify date :2016年5月17日 下午4:58:15
   */
  @RequestMapping(value = "/save")
  public ModelAndView save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    Map<String, Object> params = getBopsParams(req);
    Message message=new Message();
    String content=(String)params.get("content");
    if(content.length()>50){
      return null;
    }
    message.setContent(content);
    message.setTitle(content);
    message.setMsgType(MsgTypeEnum.SYS.getCode());
    Long mid=messageService.insert(message);
    
    Map<String,Object> paramMap=new HashMap<String, Object>();
    paramMap.put("status", MemberStatus.ON.getCode());
   
    String formUid=(String)req.getSession().getAttribute("lastLoginid");
    
    Long allCount=memberService.getCounts(paramMap);
    Integer length=100;
    Integer offset=0;
    Long arrLen=allCount/length;
    if(allCount%length>0){
      arrLen++;
    }
    Date date=new Date();
    Calendar   calendar   =   new   GregorianCalendar(); 
    calendar.setTime(date); 
    calendar.add(calendar.DATE,30);//把日期往后增加一天.整数往后推,负数往前移动 
    date=calendar.getTime();   //这个时间就是日期往后推30天的结果 
    
    
    for (int i = 0; i <arrLen; i++) {
        offset=i*length;
        paramMap.put("length", length);
        paramMap.put("offset", offset);
        List<String> uidList=memberService.getAllUid(paramMap);  
        
        List<UserMessage> umList=new ArrayList<UserMessage>();
        for (String uid : uidList) {
          UserMessage um=new UserMessage();
          um.setFromUid(formUid);
          um.setHasRead(HasReadEnum.NO.getCode());
          um.setMsgType(MsgTypeEnum.SYS.getCode());
          um.setUid(uid);
          um.setMsgId(mid);
          um.setExpireTime(date);
          umList.add(um);
        }
        userMessageService.batchInsert(umList);
    }

    return  new ModelAndView("redirect:message.htm");
  }
  

  
  /**
  * @Title: delete
  * @Description: 删除（此处是物理删除！！！）
  * @param req
  * @param resp
  * @return
  * @throws Exception
  * ModelAndView
  * @throws 
  * @creator     :yj
  * @create date :2016年5月17日 下午5:16:36
  * @modificator :yj
  * @modify date :2016年5月17日 下午5:16:36
   */
 @RequestMapping(value = "/delete")
 @ResponseBody
 public String delete(HttpServletRequest req, HttpServletResponse resp) throws Exception {
   Map<String, Object> params = getBopsParams(req);
   String idStr=(String)params.get("id");
   if(StringUtil.isNotBlank(idStr)){
     messageService.delete(Long.parseLong(idStr));
     return  "success";
   }
   return  "false";
 }
 
  
  

}
